package com.huishu.tcm.task;

import com.huishu.tcm.vo.SessionKeyVo;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

@EnableScheduling
@Component
public class SessionKeyService {

    // session key 列表
    public static List<SessionKeyVo> sessionKeyVoList = new ArrayList<>();

    // 添加session key
    public static synchronized void addSessionKey(SessionKeyVo v){
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.MINUTE,+5);
        v.setExpirationDate(calendar.getTime());
        sessionKeyVoList.add(v);
    }

    // 删除session key
    public static synchronized void removeSessionKey(String sessionKeyStr){
        for(int i = sessionKeyVoList.size() - 1; i >=0; i--){
            SessionKeyVo v = sessionKeyVoList.get(i);
            if(v.getSession_key().equals(sessionKeyStr)){
                sessionKeyVoList.remove(i);
            }
        }
    }

    //  每分钟清除过期的session key
    @Scheduled(cron = "0 0/1 * * * ?")
    public void clearExpiredVerificationCode(){
        for(int i = sessionKeyVoList.size() - 1; i >=0; i--){
            Date now = new Date();
            SessionKeyVo v = sessionKeyVoList.get(i);
            if(now.after(v.getExpirationDate())){
                removeSessionKey(v.getSession_key());
            }
        }
    }


}
